package com.wiselink.elevenstreet;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 11街基础API
 */
public abstract class ElevenStreetBaseAPI {
    public static final Logger log = LoggerFactory.getLogger(ElevenStreetBaseAPI.class);
    public static final MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
    public static final String URL = "http://api.11st.co.kr";
    private static final OkHttpClient CLIENT;

    static {
        CLIENT = new OkHttpClient.Builder()
                // 连接超时
                .connectTimeout(30, TimeUnit.SECONDS)
                // 读超时
                .readTimeout(30, TimeUnit.SECONDS)
                // 写超时
                .writeTimeout(30, TimeUnit.SECONDS)
                // 连接池配置（默认 keep-alive）
                .connectionPool(new ConnectionPool(5, 5, TimeUnit.MINUTES))
                // 自动重试
                .retryOnConnectionFailure(true)
                .build();
        log.error("ElevenBaseAPI 完成初始化");
    }

    public static OkHttpClient getClient() {
        return CLIENT;
    }

    public static String post(String requestBody, String path, String openapiKey) {
        RequestBody body = RequestBody.create(mediaType, requestBody);
        Request request = new Request.Builder()
                .url(URL + path)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .addHeader("openapikey", openapiKey)
                .post(body)
                .build();
        String result = getRequestResult(request);
        log.debug("post result: {}", result);
        return result;
    }

    private static String getRequestResult(Request request) {
        try (Response response = getClient().newCall(request).execute()) {
            if (!response.isSuccessful()) {
                log.error("{} 请求失败! code:{} message:{}", request.url().uri().getPath(), response.code(), response.message());
                throw new RuntimeException("Unexpected code " + response);
            }
            if (Objects.nonNull(response.body())) {
                try (ResponseBody responseBody = response.body()) {
                    return responseBody.string();
                } catch (IOException e) {
                    log.error("response body read error", e);
                    throw new RuntimeException("response body read error", e);
                }
            }
            return "";
        } catch (IOException e) {
            log.error("{} 请求失败: {}", request.url().uri().getPath(), e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
}
